package com.kymatrix.kycarbon.xsmd.common.redis.config;

import io.netty.channel.nio.NioEventLoopGroup;
import javax.annotation.Resource;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.Codec;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.klock.config.KlockConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ClassUtils;

/**
 * RedissonClient config
 * @author liujie
 * @date 2022/7/24
 */
@Configuration
public class RedissonConfig {

    @Resource
    private KlockConfig klockConfig;

    /**
     * 声明 RedissionClient bean
     */
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Config config = new Config();
        if (this.klockConfig.getClusterServer() != null) {
            (config.useClusterServers().setPassword(this.klockConfig.getPassword()))
                    .addNodeAddress(this.klockConfig.getClusterServer().getNodeAddresses());
        } else {
            config.useSingleServer().setAddress(this.klockConfig.getAddress())
                    .setDatabase(this.klockConfig.getDatabase()).setPassword(this.klockConfig.getPassword());
        }

        Codec codec = (Codec) ClassUtils.forName(this.klockConfig.getCodec(),
                ClassUtils.getDefaultClassLoader()).newInstance();
        config.setCodec(codec);
        config.setEventLoopGroup(new NioEventLoopGroup());
        return Redisson.create(config);
    }
}
